package swimv2.session;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;

import swimv2.entity.User;

/**
 * Session Bean implementation class SearchModuleBean
 */
@Stateless
@RemoteBinding( jndiBinding = "ISearchModuleRemote" )
public class SearchModuleBean implements ISearchModuleRemote {
	@PersistenceContext(unitName = "swimv2")
	protected EntityManager manager;
    /**
     * Default constructor. 
     */
    public SearchModuleBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public User getUser(Integer ID) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<User> getRanking(Integer count) {
		Query q= manager.createQuery("select new swimv2.session.Statistics(sum(f.punteggio), m.receiver) FROM Feedback f, Message m WHERE f.request.id= m.id GROUP BY m.receiver");
		List<Statistics> completa = (List<Statistics>)q.getResultList();
		
		List<Statistics> top = new ArrayList<Statistics>();
		
		for(int i=0; i<count; i++){
			top.add(completa.get(i));
		}
		return null;
	}

	@Override
	public List<User> getRanking(Integer count, Integer ScoreUp, Integer ScoreDown) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<User> getUsersParametric(List<Parameter> parameters) {
		List<User> utenti = new ArrayList<User>();
		Query q1 = manager.createQuery("SELECT u " +
				"FROM User u JOIN u.hasAbility h JOIN h.ability a WHERE a.name :name");
		Query q2 = manager.createQuery("SELECT u " +
				"FROM User u WHERE u.name = :name");
		Query q3 = manager.createQuery("SELECT u " +
				"FROM User u WHERE u.surname = :surname");
		
		for(Parameter token : parameters)
		{
			if(token.is("name"))
			{
				utenti.addAll(
						q2.setParameter("name", token.getValue())
							.getResultList()
				);
			}else if(token.is("surname"))
			{
				utenti.addAll(
						q3.setParameter("surname", token.getValue())
							.getResultList()
				);
			}else if(token.is("ability"))
			{
				utenti.addAll(
						q1.setParameter("name", token.getValue())
							.getResultList()
				);
			}
		}
		
		return utenti;
	}

}
